﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;

namespace SermonEditor
{
    public class ftpManager
    {
        public string uri;
        public string User;
        public string Password;

        public ftpManager()
        {   
         
            uri = Settings.UserName + ":" + Settings.Password + "@" + Settings.FtpServer;
            uri = uri.Replace("/", "%2F");
            uri = "ftp://" + uri;
            //uri = "ftp://" + Settings.FtpServer;
            User = Settings.UserName;
            Password = Settings.Password;
        }

        public string ReadAudioDataFile()
        {
            string ret = "";
            string myUri = uri + Settings.remoteXMLFile;

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(myUri);

            if (User.Contains("/"))
            {
                string[] aSplit = User.Split(new char[] { '/' });
                request.Credentials = new NetworkCredential(aSplit[1], Password, aSplit[0]);            
            }
            else
            {
                request.Credentials = new NetworkCredential(User, Password);            
            }

            request.Method = WebRequestMethods.Ftp.DownloadFile;
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream ftpRespStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(ftpRespStream);
            ret = reader.ReadToEnd();
            return ret;
        }

        public void Upload(string dir, string filename, string[] lines)
        {
            string myUir = uri + dir;
            string FileUri = myUir + filename;
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FileUri);
            request.Credentials = new NetworkCredential(User, Password);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            Stream reqStream = request.GetRequestStream();

            ASCIIEncoding enc = new ASCIIEncoding();
            foreach (string s in lines)
            {
                byte[] myData = enc.GetBytes(s);
                reqStream.Write(myData, 0, myData.Length);
            }
            reqStream.Close();
        }
    }
}